package club.samubird.simpledatahandlekit.utils;

import com.google.common.collect.Maps;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author sam
 * @date 2019/8/23 15:09
 * @description 功能描述
 */
public class MapUtils {

	public static List<Map> removeMapSomeProperties(Collection<Map<String, Object>> mapCollection, Set<String> expectRemoveProperties) {
		return mapCollection.stream().peek(
				map -> map.entrySet().removeIf(entry -> expectRemoveProperties.contains(entry.getKey()))
		).collect(Collectors.toList());
	}

	public static List<Map> convertMapDateProperties2Long(Collection<Map<String, Object>> mapCollection) {
		return mapCollection.stream().peek(
				map -> {
					for (Map.Entry<String, Object> entry : map.entrySet()) {
						Object value = entry.getValue();
						String key = entry.getKey();
						if (value instanceof Date) {
							map.put(key, ((Date) value).getTime());
						}
					}
				}
		).collect(Collectors.toList());
	}

	public static boolean hasEmptyProperties(Map map) {
		for (Object value : map.values()) {
			if (ObjectUtils.isEmpty(value)) {
				return true;
			}
		}
		return false;
	}

	public static boolean hasEmptyPropertiesWithExcludeSome(Map map, Object... exclude) {
		if (ObjectUtils.isEmpty(exclude)) {
			return hasEmptyProperties(map);
		}
		List<Object> objects = Arrays.asList(exclude);
		for (Map.Entry entry : (Set<Map.Entry>) map.entrySet()) {
			if (objects.contains(entry.getKey())) {
				continue;
			}
			if (ObjectUtils.isEmpty(entry.getValue())) {
				return true;
			}
		}
		return false;
	}

	public static Map removeEmptyProperties(Map map) {
		if (Objects.isNull(map)) {
			return Maps.newHashMap();
		}
		map.entrySet().removeIf(entry -> ObjectUtils.isEmpty(((Map.Entry) entry).getValue()));
		return map;
	}

	public static Map generateCascadeMap(Map map, String innerKey, String... excludeKeys) {
		if (Objects.isNull(map)) {
			return Maps.newHashMap();
		}
		if (map.keySet().contains(innerKey)) {
			throw new RuntimeException("innerKey: " + innerKey + " 已经存在.");
		}
		Map resultMap = Maps.newHashMap();
		Map innerMap = Maps.newHashMap();
		List<Object> objects = Arrays.asList(excludeKeys);
		for (Map.Entry entry : (Set<Map.Entry>) map.entrySet()) {
			if (objects.contains(entry.getKey())) {
				resultMap.put(entry.getKey(), entry.getValue());
			} else {
				innerMap.put(entry.getKey(), entry.getValue());
			}
		}
		resultMap.put(innerKey, innerMap);
		return resultMap;
	}



}
